package dubbo.learn.exchange;

import dubbo.learn.common.ProviderHostAndPort;
import dubbo.learn.common.RpcContext;
import dubbo.learn.common.contract.exchange.ExchangeLayerRpcInvoker;
import dubbo.learn.common.contract.transport.TransportLayerRpcInvoker;
import dubbo.learn.common.spi.SpiServiceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;

@Service
public class Sync2AsyncExchangeImpl implements ExchangeLayerRpcInvoker {

    public static ConcurrentHashMap<String, CompletableFuture<Object>> requestId2futureMap =
            new ConcurrentHashMap<>();


    @Override
    public Object invoke(ProviderHostAndPort providerHostAndPort, RpcContext rpcContext) {
        String requestId = UUID.randomUUID().toString();
        rpcContext.setRequestId(requestId);
        rpcContext.setRequestId2futureMap(requestId2futureMap);

        CompletableFuture<Object> completableFuture = new CompletableFuture<>();
        requestId2futureMap.put(requestId, completableFuture);


        /**
         * 交给具体的底层去解决
         */
        TransportLayerRpcInvoker  transportLayerRpcInvoker =
                SpiServiceLoader.loadService(TransportLayerRpcInvoker .class);

        transportLayerRpcInvoker.invoke(providerHostAndPort, rpcContext);

        Object s = null;
        try {
            s = completableFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        return s;
    }
}
